// reports.js
const { API } = require('../../../utils/api')

Page({
  data: {
    selectedPeriod: 'week', // week, month, year
    reportData: {
      totalSales: 0,
      totalVolume: 0,
      orderCount: 0,
      avgOrderValue: 0
    },
    chartData: [],
    fuelTypeData: [],
    dateRange: '',
    loading: false
  },

  onLoad() {
    // 检查并迁移历史数据
    this.migrateHistoricalData()
    this.loadReportData()
  },

  onShow() {
    // 页面显示时刷新报表数据
    this.loadReportData()
  },

  migrateHistoricalData() {
    const orders = wx.getStorageSync('fuelOrders') || []
    const records = wx.getStorageSync('fuelRecords') || []
    
    // 找出已完成但没有对应销售记录的订单
    const completedOrders = orders.filter(order => 
      order.status === 'completed' && 
      order.actualVolume && 
      order.actualAmount &&
      !records.some(record => record.orderId === order.id)
    )
    
    if (completedOrders.length > 0) {
      console.log(`发现 ${completedOrders.length} 条需要迁移的历史订单`)
      
      const newRecords = completedOrders.map(order => ({
        id: Date.now() + Math.random(),
        orderId: order.id,
        orderNo: order.orderNo,
        userId: order.userId,
        userName: order.userName,
        fuelType: order.fuelType,
        volume: parseFloat(order.actualVolume),
        amount: parseFloat(order.actualAmount),
        date: order.completeTime || order.createTime,
        timestamp: new Date(order.completeTime || order.createTime).getTime()
      }))
      
      // 合并新记录到现有记录
      const allRecords = [...newRecords, ...records]
      // 按时间戳排序
      allRecords.sort((a, b) => b.timestamp - a.timestamp)
      
      // 只保留最近500条记录
      const limitedRecords = allRecords.slice(0, 500)
      
      wx.setStorageSync('fuelRecords', limitedRecords)
      console.log('历史数据迁移完成')
    }
  },

  switchPeriod(e) {
    const period = e.currentTarget.dataset.period
    this.setData({
      selectedPeriod: period
    })
    this.loadReportData()
  },

  async loadReportData() {
    this.setData({ loading: true })
    
    try {
      const { selectedPeriod } = this.data
      const { startDate, endDate } = this.getDateRangeForAPI(selectedPeriod)
      
      // 调用后端API获取销售报表
      const response = await API.admin.getSalesReport({
        startDate: startDate,
        endDate: endDate
      })
      
      if (response && response.length > 0) {
        // 计算统计数据
        const reportData = this.calculateReportDataFromAPI(response)
        
        // 生成图表数据
        const chartData = this.generateChartDataFromAPI(response, selectedPeriod)
        
        // 按油品类型统计
        const fuelTypeData = this.calculateFuelTypeDataFromAPI(response)
        
        // 设置日期范围
        const dateRange = this.getDateRange(selectedPeriod)

        this.setData({
          reportData,
          chartData,
          fuelTypeData,
          dateRange
        })
      } else {
        // 没有数据，显示空状态
        this.setData({
          reportData: {
            totalSales: '0.00',
            totalVolume: '0.00',
            orderCount: 0,
            avgOrderValue: '0.00'
          },
          chartData: [],
          fuelTypeData: [],
          dateRange: this.getDateRange(selectedPeriod)
        })
      }
    } catch (error) {
      console.error('获取报表数据失败:', error)
      // 如果API调用失败，回退到本地存储方式
      this.loadReportDataFromLocal()
    } finally {
      this.setData({ loading: false })
    }
  },

  loadReportDataFromLocal() {
    const { selectedPeriod } = this.data
    const records = wx.getStorageSync('fuelRecords') || []
    
    // 根据选择的时间段过滤数据
    const filteredRecords = this.filterRecordsByPeriod(records, selectedPeriod)
    
    // 计算统计数据
    const reportData = this.calculateReportData(filteredRecords)
    
    // 生成图表数据
    const chartData = this.generateChartData(filteredRecords, selectedPeriod)
    
    // 按油品类型统计
    const fuelTypeData = this.calculateFuelTypeData(filteredRecords)
    
    // 设置日期范围
    const dateRange = this.getDateRange(selectedPeriod)

    this.setData({
      reportData,
      chartData,
      fuelTypeData,
      dateRange
    })
  },

  filterRecordsByPeriod(records, period) {
    const now = new Date()
    let startDate

    switch (period) {
      case 'week':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        break
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1)
        break
      default:
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    }

    return records.filter((record) => {
      const recordDate = new Date(record.date)
      return recordDate >= startDate && recordDate <= now
    })
  },

  calculateReportData(records) {
    let totalSales = 0
    let totalVolume = 0
    const orderCount = records.length

    records.forEach((record) => {
      totalSales += record.amount
      totalVolume += record.volume
    })

    const avgOrderValue = orderCount > 0 ? totalSales / orderCount : 0

    return {
      totalSales: totalSales.toFixed(2),
      totalVolume: totalVolume.toFixed(2),
      orderCount,
      avgOrderValue: avgOrderValue.toFixed(2)
    }
  },

  generateChartData(records, period) {
    const dataMap = new Map()
    
    records.forEach((record) => {
      const date = new Date(record.date)
      let key

      switch (period) {
        case 'week':
          key = `${date.getMonth() + 1}/${date.getDate()}`
          break
        case 'month':
          key = `${date.getDate()}日`
          break
        case 'year':
          key = `${date.getMonth() + 1}月`
          break
        default:
          key = `${date.getMonth() + 1}/${date.getDate()}`
      }

      if (!dataMap.has(key)) {
        dataMap.set(key, { sales: 0, volume: 0, orders: 0 })
      }

      const data = dataMap.get(key)
      data.sales += record.amount
      data.volume += record.volume
      data.orders += 1
    })

    return Array.from(dataMap.entries()).map(([date, data]) => ({
      date,
      sales: data.sales.toFixed(2),
      volume: data.volume.toFixed(2),
      orders: data.orders
    }))
  },

  calculateFuelTypeData(records) {
    const typeMap = new Map()

    records.forEach((record) => {
      const type = record.fuelType
      if (!typeMap.has(type)) {
        typeMap.set(type, { sales: 0, volume: 0, orders: 0 })
      }

      const data = typeMap.get(type)
      data.sales += record.amount
      data.volume += record.volume
      data.orders += 1
    })

    return Array.from(typeMap.entries()).map(([type, data]) => ({
      type,
      sales: data.sales.toFixed(2),
      volume: data.volume.toFixed(2),
      orders: data.orders,
      percentage: 0 // 将在模板中计算
    }))
  },

  getDateRange(period) {
    const now = new Date()
    let startDate

    switch (period) {
      case 'week':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        return `${this.formatDate(startDate)} - ${this.formatDate(now)}`
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        return `${now.getFullYear()}年${now.getMonth() + 1}月`
      case 'year':
        return `${now.getFullYear()}年`
      default:
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        return `${this.formatDate(startDate)} - ${this.formatDate(now)}`
    }
  },

  formatDate(date) {
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${month}/${day}`
  },

  getDateRangeForAPI(period) {
    const now = new Date()
    let startDate

    switch (period) {
      case 'week':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        break
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1)
        break
      default:
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    }

    return {
      startDate: startDate.toISOString().split('T')[0], // YYYY-MM-DD格式
      endDate: now.toISOString().split('T')[0]
    }
  },

  calculateReportDataFromAPI(reports) {
    let totalSales = 0
    let totalVolume = 0
    let orderCount = 0

    reports.forEach((report) => {
      totalSales += report.totalAmount
      totalVolume += report.totalVolume
      orderCount += report.totalOrders
    })

    const avgOrderValue = orderCount > 0 ? totalSales / orderCount : 0

    return {
      totalSales: totalSales.toFixed(2),
      totalVolume: totalVolume.toFixed(2),
      orderCount,
      avgOrderValue: avgOrderValue.toFixed(2)
    }
  },

  generateChartDataFromAPI(reports, period) {
    return reports.map((report) => {
      const date = new Date(report.date)
      let displayDate

      switch (period) {
        case 'week':
          displayDate = `${date.getMonth() + 1}/${date.getDate()}`
          break
        case 'month':
          displayDate = `${date.getDate()}日`
          break
        case 'year':
          displayDate = `${date.getMonth() + 1}月`
          break
        default:
          displayDate = `${date.getMonth() + 1}/${date.getDate()}`
      }

      return {
        date: displayDate,
        sales: report.totalAmount.toFixed(2),
        volume: report.totalVolume.toFixed(2),
        orders: report.totalOrders
      }
    })
  },

  calculateFuelTypeDataFromAPI(reports) {
    const typeMap = new Map()

    reports.forEach((report) => {
      if (report.fuelTypeData) {
        report.fuelTypeData.forEach((fuelData) => {
          const type = fuelData.fuelType
          if (!typeMap.has(type)) {
            typeMap.set(type, { sales: 0, volume: 0, orders: 0 })
          }

          const data = typeMap.get(type)
          data.sales += fuelData.amount
          data.volume += fuelData.volume
          data.orders += fuelData.orders
        })
      }
    })

    return Array.from(typeMap.entries()).map(([type, data]) => ({
      type,
      sales: data.sales.toFixed(2),
      volume: data.volume.toFixed(2),
      orders: data.orders,
      percentage: 0 // 将在模板中计算
    }))
  },

  exportReport() {
    wx.showModal({
      title: '导出报表',
      content: '报表导出功能开发中，敬请期待',
      showCancel: false
    })
  },

  refreshData() {
    wx.showLoading({
      title: '刷新中...'
    })
    
    setTimeout(() => {
      this.loadReportData()
      wx.hideLoading()
      wx.showToast({
        title: '数据已刷新',
        icon: 'success'
      })
    }, 1000)
  }
})